package com.projectplace.GUI.Database;

/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.util.List;
import java.util.concurrent.SynchronousQueue;

import com.google.gson.Gson;
import com.projectplace.api.objectResponses.Project;
import com.projectplace.api.objectResponses.Conversation.Conversation;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import com.projectplace.GUI.Callback.CacheCallbackInterface;
import com.projectplace.GUI.Callback.CacheHelperCallbackWrapper;
import com.projectplace.GUI.Callback.InternalCacheCallback;
import com.projectplace.GUI.Callback.InternalCompareCallback;


/**
 * Class for saving and loading objects to/from the SDCard, will be saved in JSON in the same format as they 
 * are received from the server.
 */
public class CacheHelper {
	
	private static final String LOG_TAG = "CacheHelper";
	private static final String myProjectsFileName = "myproject";
	private static Gson gson = new Gson();
	
	public static void deleteAllFiles(Context c){
		for(String s:c.fileList()){
			c.deleteFile(s);
		}
	}
	
	/**
	 * Saves your project's to SDCard on a file with the help of a new thread so
	 * it doesnt block the UI thread
	 */
	public static void saveMyProjects(Context context, List<Project> myProjects) {
			try {
				Log.d(LOG_TAG, "Saving Projects.....");
				new SaveToCache(context, myProjectsFileName,
						gson.toJson(myProjects), new InternalCacheCallback() {
							public void onSuccess(String response) {
								Log.d(LOG_TAG, response);
							}

							public void onFail(Error err) {
								Log.d(LOG_TAG, err.getMessage());
							}
						}).start();
			} catch (RuntimeException e) {
				Log.d(LOG_TAG,
						"RuntimeException means that Gson can't Serialize List<Project>");
			}
	}

	/**
	 * Saves a specific projectconversation to SDCard. The file name is the id
	 * of the projectconversation.
	 */
	public static void saveMyProjectConversations(Context context,List<Conversation> projectConversation, String idAsFileName) {
			try {
				Log.d(LOG_TAG, "Saving ProjectConversation.....");
				new SaveToCache(context, idAsFileName,
						gson.toJson(projectConversation),
						new InternalCacheCallback() {
	
							public void onSuccess(String response) {
								Log.d(LOG_TAG, response);
							}
	
							public void onFail(Error err) {
								Log.d(LOG_TAG, err.getMessage());
							}
						}).start();
			} catch (RuntimeException e) {
				Log.d(LOG_TAG,
						"RuntimeException means that Gson can't Serialize List<Conversation>");
			}
	}

	/**
	 * Saves a specific conversation to SDCard. The conversation id is the file
	 * name
	 * 
	 */
	public static void saveMyConversation(Context context,
			Conversation conversation, String idAsFileName) {
		try {
			Log.d(LOG_TAG, "Saving Conversation.....");
			new SaveToCache(context, idAsFileName, gson.toJson(conversation),
					new InternalCacheCallback() {

						public void onSuccess(String response) {
							Log.d(LOG_TAG, response);
						}

						public void onFail(Error err) {
							Log.d(LOG_TAG, err.getMessage());
						}
					}).start();
		} catch (RuntimeException e) {
			Log.d(LOG_TAG,
					"RuntimeException means that Gson can't Serialize List<Conversation>");
		}
	}
	
	/**
	 * Method will return a List<Project> on the callback interface or a Error. Typically an Error will allways occur if it the first
	 * time a user starts the app
	 * @param Context context
	 * @param Handler handler
	 * @param String projectId
	 * @param CacheCallbackInterface.ResponseMyProjects callback
	 **/
	public static void getMyProjects(Context context,final Handler handler,final CacheCallbackInterface.ResponseMyProjects callback){
			new LoadFromCache(context, myProjectsFileName, new InternalCacheCallback() {
				public void onSuccess(String response) {
					CacheHelperCallbackWrapper.loadMyProjects load = new CacheHelperCallbackWrapper.loadMyProjects(callback);
					load.setResponse(response);
					handler.post(load);
				}
				public void onFail(Error err) {
					Log.d(LOG_TAG, err.getMessage());
					CacheHelperCallbackWrapper error = new CacheHelperCallbackWrapper(callback);
					error.setError(err); 
					handler.post(error);
				}
			}).start();
	}
	
	
	/**
	 * This method will return a List<Conversation> on the callback interface or an Error if an error has occured.  Typically an Error will allways occur if it the first
	 * time a user views a projectConversation
	 * @param Context context
	 * @param Handler handler
	 * @param String projectId
	 * @param CacheCallbackInterface.ResponseProjectConversation callback
	 **/
	public static void getMyProjectConversation(Context context,final Handler handler,String projectId, final CacheCallbackInterface.ResponseProjectConversation callback){		
		
			new LoadFromCache(context, projectId, new InternalCacheCallback() {
				public void onSuccess(String response) {
					CacheHelperCallbackWrapper.loadProjectConversation load = new CacheHelperCallbackWrapper.loadProjectConversation(callback);
					load.setResponse(response);
					if(handler.sendEmptyMessageDelayed(1, 10));
						handler.post(load);
				}
				public void onFail(Error err) {
					Log.d(LOG_TAG, err.getMessage());
					CacheHelperCallbackWrapper error = new CacheHelperCallbackWrapper(callback);
					error.setError(err);
					handler.post(error);
				}
			}).start();
		
	}
	
	/**
	 *  Will return a Conversation object to the callback interface or an Error if an error has occured.  Typically an Error will allways occur if it the first
	 * time a user views a conversation
	 * @param Context context
	 * @param Handler handler
	 * @param String projectConversationId
	 * @param CacheCallbackInterface.ResponseConversation callback
	 **/
	public static void getMyConversation(Context context,final Handler handler,String ConversationId, final CacheCallbackInterface.ResponseConversation callback){
			new LoadFromCache(context, ConversationId, new InternalCacheCallback() {
				public void onSuccess(String response) {
					CacheHelperCallbackWrapper.loadConversation load = new CacheHelperCallbackWrapper.loadConversation(callback);
					load.setResponse(response);
					handler.post(load);
				}
				public void onFail(Error err) {
					Log.d(LOG_TAG, err.getMessage());
					CacheHelperCallbackWrapper error = new CacheHelperCallbackWrapper(callback);
					error.setError(err);
					handler.post(error);
				}
			}).start();
	}
	
	
	public static void CompareTwoListConversations(List<Conversation> cachedList, List<Conversation> apiList,final Handler handler, final CacheCallbackInterface.ReponseCompareConversations callback) {
		try {
			Log.d(LOG_TAG, "Saving Projects.....");
			new CompareConversation(cachedList, apiList,
					 new InternalCompareCallback() {
						
						public void onSuccess(List<Conversation> upToDateConversationsList) {
							// TODO Auto-generated method stub
							CacheHelperCallbackWrapper.compareConversationsList load = new CacheHelperCallbackWrapper.compareConversationsList(callback,upToDateConversationsList);
							handler.post(load);
						}
						
						public void onFail(Error err) {
							// TODO Auto-generated method stub
							Log.d(LOG_TAG, err.getMessage());
							CacheHelperCallbackWrapper error = new CacheHelperCallbackWrapper(callback,err);
							handler.post(error);
						}
					}).start();
		} catch (RuntimeException e) {
			Log.d(LOG_TAG,
					"RuntimeException means that Gson can't Serialize List<Project>");
		}
	}
}
